package com.factory.iamp.controller;

import com.factory.iamp.pojo.TableTemplateTail;
import com.factory.iamp.pojo.User;
import com.factory.iamp.service.TableTemplateTailService;
import com.factory.iamp.utils.helper.PageHelper;
import com.factory.iamp.utils.token.LoginToken;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Map;

@RestController
@RequestMapping("/table/template/tail")
@Validated
public class TableTemplateTailController {
    @Resource
    private TableTemplateTailService tableTemplateTailService;

    @GetMapping("/list/{limit}/{page}")
    @LoginToken
    public PageHelper getAllTableTemplateTail(
            @PathVariable("limit") int limit,
            @PathVariable("page") int page,
            @RequestAttribute("iampUser") User user
    ) {
        PageHelper result = new PageHelper(tableTemplateTailService.Count(user.getLine()), page, limit);
        result.setData(tableTemplateTailService.ListPaged(result, user.getLine()));
        return result;
    }

    @GetMapping("/find/name/{limit}/{page}")
    @LoginToken
    public PageHelper findTableTemplateBodyByName(
            @PathVariable("limit") int limit,
            @PathVariable("page") int page,
            @RequestParam("name") String name,
            @RequestAttribute("iampUser") User user
    ) {
        name += "%";
        PageHelper result = new PageHelper(tableTemplateTailService.findByNameCount(name, user.getLine()), page, limit);
        result.setData(tableTemplateTailService.findByNameListPaged(result, name, user.getLine()));
        return result;
    }

    @PostMapping("/add")
    @LoginToken(checkPrivate = true)
    public TableTemplateTail addTableTemplateTail(
            @RequestParam("name") @NotBlank String name,
            @RequestParam("file") MultipartFile file,
            @RequestParam("json") String json,
            @RequestParam(name = "defaultValue", defaultValue = "") String defaultValue,
            @RequestAttribute("iampUser") User user
    ) throws Throwable {
        return tableTemplateTailService.addTableTemplateTail(name, file, json, defaultValue, user.getLine());
    }

    @PostMapping("/set/{oid}/json")
    @LoginToken(checkPrivate = true)
    public void SetTableTemplateTailJson(
            @PathVariable("oid") int oid,
            @RequestBody Map<String, String> data
    ) {
        tableTemplateTailService.setJson(oid, data.get("json"));
    }

    @DeleteMapping("/{oid}")
    @LoginToken(checkPrivate = true)
    public void deleteTableTemplateTail(@PathVariable("oid") int oid, @RequestAttribute("iampUser") User user) {
        tableTemplateTailService.deleteTableTemplateTail(oid, user.getLine());
    }
}
